const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");
const {setBillNo, toAccounted} = require("../bill/base");
// 确认派单收款
// 派单收款审核
router.post('/receipt/donerp', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId;
    let body = ctx.request.body;
    let list = body.infos;
    if(list.length===0) return ctx.err('没有收款列表')
    let billNo = await setBillNo(tenantId, 153001)
    let transType = 153001
    let invoice = {
        tenantId,
        cby: user.id,
        printNo: 0,
        billState: 'draft',
        billNo: billNo,
        billDate: body.billDate,
        billType: 'RECEIPT',
        transType,
        transTypeName: '收款单',
        totalAmount: body.totalAmount,
        disAmount: body.disAmount,
        amount: body.amount,
        buId: body.buId,
        accId: body.accId,
        accId1: body.accId,
        accAmount: body.accAmount,
        accAmount1: body.accAmount1,
        doId: body.doId,
        salesId: body.doId,
        yhAmount: body.disAmount,
        createdAt: tool.getTime(),
        accountedBy: user.id,
        accountedAt: tool.getTime(),
        orgin: '派单生成'
    }
    let receipts = []
    list.map(row => {
        receipts.push({
            tenantId,
            iid: 0,
            transType,
            billId: row.billId,
            srcBillNo: row.billNo,
            srcBillType: 'SALE',
            srcTransTypeName: row.transTypeName,
            srcTransType: row.transType,
            arrears: tool.xe.toNumber(row.arrearsReal),
            leftAmount: tool.xe.toNumber(row.leftAmount),
            nowCheck: tool.xe.toNumber(row.nowCheck),
            yhAmount: tool.xe.toNumber(row.yhAmount),
        })
    })
    // invoice.yhAmount = tool.xe.sum(receipts, 'yhAmount')
    await db.transaction(async () => {
        let ret = await db.models['invoice'].create(invoice)
        receipts.map(row => {
            row.iid = ret.id
        })
        await db.models['invoiceReceipt'].bulkCreate(receipts)
        await toAccounted(ctx, [ret.id])
        //
        for (let i = 0; i < list.length; i++) {
            let model = await db.models['receiptPd'].findOne({
                where: {
                    tenantId,
                    id: list[i].id,
                    state: '收款中'
                }
            })
            if(model) {
                model.nowCheck = list[i].nowCheck
                model.yhAmount = tool.xe.toNumber(list[i].yhAmount)
                model.state = '已收款'
                model.doneAt = tool.getTime()
                model.doneBy = user.id
                model.doneByName = user.name
                await model.save()
            }
        }
    })

    return ctx.suc('审核成功')
})
module.exports = router;
